<?php

defined('AUTH_SERVICE') or define('AUTH_SERVICE','live');

require_once '../server.php';

// Specify true to log messages to Web server logs.
$DEBUG = false;

$OFFERS = 'WL.Basic,WL.Emails';

// $OFFERS = 'WL.Basic,WL.Emails,Contacts.View';
// Comma-delimited list of offers to be used.

// Application key file: store in an area that cannot be
// accessed from the Web.
$KEYFILE = APP_PATH . '/live/config.xml';

// Name of cookie to use to cache the consent token.
$COOKIE = 'delauthtoken-contact';

$COOKIETTL = time() + (10 * 365 * 24 * 60 * 60);

// URL of Delegated Authentication index page.

$HANDLER = 'delauth-handler.php';
// Default handler for Delegated Authentication.

$PROXY_SVR = "";

include 'windowslivelogin.php';



$wll = WindowsLiveLogin::initFromXml($KEYFILE);

$consenturl = $wll -> getConsentUrl($OFFERS);

// If the raw consent token has been cached in a site cookie, attempt to
// process it and extract the consent token.
$token = null;

$cookie = @$_COOKIE[$COOKIE];

if ($cookie)
{
    $token = $wll -> processConsentToken($cookie);
}

//Check if there's consent and, if not, redirect to the login page

if (!$token)
{
    $token = null;
}

if ($token && !$token -> isValid())
{
    $token = null;
}


if ($token == null)
{
    header('Location:' . $consenturl);
}

if ($token)
{

    $uri = 'https://apis.live.net/v5.0/me?access_token=' . $token -> getDelegationToken();

    // $uri =
    // "https://livecontacts.services.live.com/users/@C@".$output."/LiveContacts";
    $session = curl_init($uri);

    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($session, CURLOPT_USERAGENT, "Windows Live Data Interactive SDK");
    curl_setopt($session, CURLOPT_HTTPHEADER, array("Authorization: DelegatedToken dt=\"" . $token -> getDelegationToken() . "\""));
    curl_setopt($session, CURLOPT_VERBOSE, 1);
    curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, TRUE);
    curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($session, CURLOPT_TIMEOUT, 120);
    $response = curl_exec($session);
    curl_close($session);

    $data =  json_decode($response,1);
    
    
    //processCentralServiceResponseData($data);
    processCentralServiceResponseData($data);
    
    // process data then return what happend here.
}
